package com.jiang.droidsms.ui.adapter;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jiang.droidsms.R;
import com.jiang.droidsms.data.SMSTable.SMS;

/**
 * The Class ConversationListAdapter.
 */
public class ConversationListAdapter extends CursorAdapter {
	
	SimpleDateFormat mFormat = new SimpleDateFormat("MM-dd HH:mm:ss E");

	/**
	 * Instantiates a new conversation list adapter.
	 * 
	 * @param context
	 *            the context
	 * @param c
	 *            the c
	 */
	public ConversationListAdapter(Context context, Cursor c) {
		super(context, c, true);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.CursorAdapter#bindView(android.view.View,
	 * android.content.Context, android.database.Cursor)
	 */
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		LinearLayout layout = (LinearLayout) view;
		String msg = cursor.getString(cursor.getColumnIndex(SMS.BODY));
		TextView content = (TextView) layout.findViewById(R.id.body);
		content.setText(msg);
		TextView time = (TextView) view.findViewById(R.id.time);
		Date now = new Date(cursor.getLong(cursor.getColumnIndex(SMS.DATE)));
		String timeStr = mFormat.format(now);
		time.setText(timeStr);
		int type = cursor.getInt(cursor.getColumnIndex(SMS.TYPE));
		switch (type) {
		case SMS.TYPE_SMS_SEND_ERROR:
		case SMS.TYPE_SMS_OUT:
			layout.setGravity(Gravity.RIGHT);
			layout.setPadding(30, 0, 0, 0);
			time.setPadding(0, 0, 30, 0);
			content.setBackgroundResource(R.drawable.conversation_out_bg);
			content.setClickable(true);
			break;
		case SMS.TYPE_SMS_IN:
			layout.setGravity(Gravity.LEFT);
			layout.setPadding(0, 0, 30, 0);
			time.setPadding(30, 0, 0, 0);
			content.setBackgroundResource(R.drawable.conversation_in_bg);
			break;
		case SMS.TYPE_SMS_DRAFT:
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.CursorAdapter#newView(android.content.Context,
	 * android.database.Cursor, android.view.ViewGroup)
	 */
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		LinearLayout layout = (LinearLayout) LayoutInflater.from(context)
				.inflate(R.layout.conversation_list_adapter, null);
		return layout;
	}

}
